package org.gokulam.cgfw.core;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.exolab.castor.xml.XMLContext;
import org.gokulam.cgfw.data.Entity;
import org.gokulam.cgfw.data.Field;

public class XmlMetaDataManager extends MetaDataManager {

	
	
	/* (non-Javadoc)
	 * @see org.gokulam.cgfw.core.MetaDataManager#load(java.lang.String)
	 */
	public void load(String path){
		
		// initialize and configure XMLContext

		XMLContext context = new XMLContext();


		// Create a new Unmarshaller
		Unmarshaller unmarshaller = context.createUnmarshaller();
		unmarshaller.setClass(Entity.class);

		try {
			// Create a Reader to the file to unmarshal from
			FileReader reader = new FileReader("Entity.xml");
			// Unmarshal the person object
			entity = (Entity) unmarshaller.unmarshal(reader);
			
			System.out.println(((Field)entity.getFields().get(0)).getName());
			System.out.println(((Field)entity.getFields().get(0)).getType());
		} catch (MarshalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ValidationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void create() {
		/*Person person = new Person();
		
		person.setDoorNumber(12);
		person.setName("Randheer");
		person.setStreet("Commercial Street");
		*/
		
		Entity entity = new Entity();
		entity.setName("Customer");
		Field fld = new Field();
		fld.setName("name");
		
		entity.addField(fld);
		fld = new Field();
		fld.setName("location");
		entity.addField(fld);
		// create a Writer to the file to marshal to
		try {
			Writer writer = new FileWriter("Entitynew.xml");
			XMLContext context = new XMLContext();
			
			// create a new Marshaller
			Marshaller marshaller = context.createMarshaller();
			marshaller.setWriter(writer);

			// marshal the person object
			marshaller.marshal(entity);
		} catch (MarshalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ValidationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		XmlMetaDataManager dm = new XmlMetaDataManager();
		dm.create();
		dm.load("./");
	}

}
